package com.catazy.mvvmlib.net.network

import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import com.blankj.utilcode.util.LogUtils

/**
 * 作者: Tao
 * 日期: 2024/1/24
 * 时间: 16:52
 * 描述: 网络状态回调的实现类
 */
class NetworkCallbackImpl : ConnectivityManager.NetworkCallback() {

    //标识位，标识是否正在更改状态，避免同时更改状态
    private var isChange = false

    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        LogUtils.i("网络已连接")
        if (!isChange) {
            isChange = true
            NetworkStateManager.instance.mNetworkStateCallback.value?.let {
                if (!it.isSuccess) {
                    NetworkStateManager.instance.mNetworkStateCallback.postValue(NetState(isSuccess = true))

                }
                return
            }
            NetworkStateManager.instance.mNetworkStateCallback.postValue(NetState(isSuccess = true))
        }
        isChange = false
    }

    override fun onLosing(network: Network, maxMsToLive: Int) {
        super.onLosing(network, maxMsToLive)
        LogUtils.i("网络即将断开")
    }

    override fun onLost(network: Network) {
        super.onLost(network)
        LogUtils.i("网络已断开")
        if (!isChange) {
            isChange = true
            NetworkStateManager.instance.mNetworkStateCallback.value?.let {
                if (it.isSuccess) {
                    NetworkStateManager.instance.mNetworkStateCallback.postValue(NetState(isSuccess = false))

                }
                return
            }
            NetworkStateManager.instance.mNetworkStateCallback.postValue(NetState(isSuccess = false))
        }
        isChange = false
    }

    override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
//                LogUtil.i("网络发生变更，类型为：WIFI")
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
//                LogUtil.i("网络发生变更，类型为：移动网络")
            } else {
//                LogUtil.i("网络发生变更，类型为：其他")
            }
        }
    }

}